// page/Home.js
import Notify from '@vant/weapp/lib/notify/notify';
const {
  hourSpendList,
  weekDays
} = require('../config/map')

function curTime() {
  const date = new Date();
  const hour = date.getHours()
  const minutes = date.getMinutes()
  return (hour < 10 ? "0" + hour : hour) + ':' + (minutes < 10 ? "0" + minutes : minutes);
}
const db = wx.cloud.database()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    course: {
      name: {
        value: '',
        error: '',
      },
      courseName: {
        value: '',
        error: '',
      },
      totalHour: {
        value: 0,
        error: '',
      },
      resetHour: {
        value: 0,
        error: '',
      },
      remark: {
        value: '',
        error: '',
      },
      schoolTime: {
        value: [],
        error: '',
      },
    },
    hourSpendList,
    curEditSchool: -1,
    curHourSpend: {
      value: "1",
      text: "1课时"
    },
    weekDays,
    weekShow: false,
    curWeek: 0,
    timeShow: false,
    currentDate: '12:00',
    curTimeType: '',
  },
  addHour() {
    this.setData({
      show: true,
    });
  },
  addHourLine() {
    this.data.course.schoolTime.value.push(['0', curTime(), curTime()]);
    this.setData({
      course: this.data.course,
    });
  },
  onCancel() {
    this.setData({
      show: false,
    });
  },
  onConfirm(e) {
    const value = e.detail.value;
    this.setData({
      curHourSpend: value,
      show: false,
    });
  },
  changeWeek() {
    this.setData({
      weekShow: true,
    });
  },
  changeSchoolWeek(e) {
    this.setData({
      curEditSchool: e.currentTarget.dataset.id,
      weekShow: true,
    });
  },
  onWeekCancel() {
    this.setData({
      weekShow: false,
    });
  },
  onWeekConfirm(e) {
    const {
      curEditSchool,
      course
    } = this.data;
    if (curEditSchool === -1) return;
    course.schoolTime.value[curEditSchool][0] = e.detail.index;
    this.setData({
      weekShow: false,
      curWeek: e.detail.index,
      course,
    });
  },
  onTimeCancel() {
    this.setData({
      timeShow: false,
    });
  },
  changeSchoolTime(e) {
    const {
      type,
      id
    } = e.currentTarget.dataset;
    this.setData({
      timeShow: true,
      curEditSchool: id,
      curTimeType: type,
    });
  },
  compareTime(start, end) {
    return end > start
  },
  onTimeConfirm(e) {
    const {
      curEditSchool,
      course,
      curTimeType: type,
      currentDate
    } = this.data;
    if (curEditSchool === -1 || !type) return;
    if (type === 'startTime') {
      if (!this.compareTime(currentDate, course.schoolTime.value[curEditSchool][2])) return Notify({
        message: '上课时间的开始时间大于结束时间',
        color: 'white',
        background: 'red',
      });
      course.schoolTime.value[curEditSchool][1] = currentDate;
    } else {
      if (!this.compareTime(course.schoolTime.value[curEditSchool][1], currentDate)) return Notify({
        message: '上课时间的结束时间小于开始时间',
        color: 'white',
        background: 'red',
      });
      course.schoolTime.value[curEditSchool][2] = currentDate;
    }
    this.setData({
      timeShow: false,
      curWeek: e.detail.index,
      course,
    });
  },
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },
  onChange(event) {
    const {
      type
    } = event.currentTarget.dataset;
    const {
      course
    } = this.data;
    course[type].value = event.detail;
    // event.detail 为当前输入的值
    this.setData({
      course,
    });
  },
  addHour() {
    console.log(1);
    this.setData({
      show: true,
    });
  },
  createCourse() {
    let isValidate = true;
    let schoolRes = []
    const {
      course,
      curHourSpend
    } = this.data;
    if (course.courseName.value.trim().length === 0) {
      course.courseName.error = '请输入课程名称';
      isValidate = false;
    }
    if (course.name.value.trim().length === 0) {
      course.name.error = '请输入课程名称';
      isValidate = false;
    }
    if (course.totalHour.value < 0) {
      course.totalHour.error = '总课时输入不正确';
      isValidate = false;
    }
    if (course.resetHour.value < 0) {
      course.resetHour.error = '剩余课时输入不正确';
      isValidate = false;
    }
    if (course.resetHour.value > course.totalHour.value) {
      course.resetHour.error = '剩余课时不能大于总课时';
      isValidate = false;
    }
    if (isValidate) {
      const res = {};
      for (const key in course) {
        if (key === 'schoolTime') {
          schoolRes = course[key].value.filter(val => val[0] != '0')
          schoolRes = schoolRes.map(val => {
            return weekDays[val[0]] + ' ' + val[1] + " " + val[2]
          }).join(',')
          res[key] = schoolRes;
        } else {
          res[key] = course[key].value;
        }
        course[key].error = '';
      }
      res['hourSpend'] = curHourSpend
      res['createTime'] = new Date()
      db.collection('course')
        .add({
          data: {
            ...res,
          },
        })
        .then((res) => {
          if (res.errMsg === 'collection.add:ok') {
            wx.showToast({
              title: '成功',
              icon: 'success',
              duration: 2000
            })
            wx.switchTab({
              url: '/page/home/index',
              success: function () {
                let pageHome = getApp().globalData.pageHome;
                if (pageHome) {
                  pageHome.refreshData();
                }
              }
            })
          }
        });
    }

    this.setData({
      course,
    });
  },
});